package com.dongdongshop.service.impl;

import com.dongdongshop.domain.model.TbSeller;
import com.dongdongshop.domain.vo.SellerVO;
import com.dongdongshop.mapper.TbSellerMapper;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SellerServiceImpl implements SellerService {

    @Autowired
    private TbSellerMapper sellerMapper;

    @Override
    public SellerVO sellerByName(String sellerId) {
        TbSeller tbSeller = sellerMapper.selectByPrimaryKey(sellerId);
        if (tbSeller == null){
            return null;
        }
        SellerVO sellerVO = new SellerVO();
        BeanUtils.copyProperties(tbSeller,sellerVO);
        return sellerVO;
    }

    @Override
    public void sellerAdd(SellerVO vo) throws Exception {
        TbSeller tbSeller = new TbSeller();
        BeanUtils.copyProperties(vo,tbSeller);
        //查询是否有重复的登录名
        String sellerId = tbSeller.getSellerId();
        TbSeller tbSeller1 = sellerMapper.selectByPrimaryKey(sellerId);
        if (tbSeller1 != null){
            //如果有相同的登录名, 则抛出一个异常
            throw new Exception();
        }
        //如果没有重复的id, 密码加密并增加
        String password = tbSeller.getPassword();
        String s = ShiroUtils.generateSalt(6);
        String md5 = ShiroUtils.encryptPassword("MD5", password, s, 3);
        tbSeller.setPassword(md5);
        tbSeller.setSalt(s);
        sellerMapper.insertSelective(tbSeller);
    }

    @Override
    public List<SellerVO> sellerList() {
        List<TbSeller> tbSellers = sellerMapper.selectByExample(null);
        return tbSellers.stream().map(tbSeller -> {
            SellerVO sellerVO = new SellerVO();
            BeanUtils.copyProperties(tbSeller, sellerVO);
            return sellerVO;
        }).collect(Collectors.toList());
    }

    @Override
    public void updateState(String sellerId, int state) {
        TbSeller tbSeller = sellerMapper.selectByPrimaryKey(sellerId);
        if (state == 1){
            tbSeller.setStatus("1");
        } else if (state == 2) {
            tbSeller.setStatus("2");
        } else if (state == 3) {
            tbSeller.setStatus("3");
        }
        sellerMapper.updateByPrimaryKeySelective(tbSeller);
    }
}
